var tooMuchText = " You can't add to cart more 10,000 pieces.";

function addCommodity(id) {
    var dataString = 'id=' + id + '&action=add';
    sendRequest(dataString);
}

function removeCommodity(id) {
    console.log(id);
    var dataString = 'id=' + id + '&action=remove';
    sendRequest(dataString);
}

function changeCommodityQuantity(id, obj) {
    var quantity = Math.floor($(obj).val());
    console.log(id);
    console.log(quantity);

    if ((quantity < 1) || (quantity > 10000)) {
        quantity = 1;
        $(obj).val(1);
    } else {
        $(obj).val(quantity);
    }
    var dataString = 'id=' + id + '&action=count' + '&quantity=' + quantity;
    sendRequest(dataString);
}

function is_positive_int(event, value) {
    var old_value = value;
    var c = String.fromCharCode(event.keyCode);
    var new_value = old_value + c;
    return ((validate(new_value, '^[1-9]{1}[0-9]{0,4}?$')) || (event.keyCode==8)
                    || (event.keyCode == 37)
                    || (event.keyCode == 39)
                    || (event.keyCode == 46));
}

function sendRequest(dataString) {
    $.ajax({
        type: "POST",
        url: "Cart",
        data: dataString,
        success: function(data) {
            if (data.answer === "ok") {
                $('#totalCostHeader').html('(' + data.totalCost + ' $)');
                $('#totalCostCart').html(data.totalCost);
                $('#goodsCount').html(data.commoditiesCount);
                if (data.totalCost == 0) {
                    $('#proceed_btn').hide();
                }
            }
            if (typeof(data.tooMuch) !== 'undefined') {
                showAddedBlock(data.tooMuch, tooMuchText);
            }
        }
    });
}

function showAddedBlock(name, endText) {
        var block = $('<div class="added">' + ' <span>' 
                + name + '</span> ' + endText+ '</div>');
        $("#container").append(block);
        block.fadeIn(400);

        setTimeout(function() {
            block.fadeOut(400);
        }, 2500);

        setTimeout(function() {
            block.remove();
        }, 2900);
    }

$(document).ready(function() {
    var addText = " added to cart.";
    $(".btn-buy").click(function() {
        var name = $(this).parents(".box-prod").find("h4").html();
        showAddedBlock(name, addText);
    });

    $(".input").click(function() {
        var name = $(this).parents(".float_left").find("h2").html();
        showAddedBlock(name, addText);
    });

//    $("input[type=number]").keyup(function() {
//        var number = Math.floor($(this).val());
//        if (number < 1) {
//            $(this).val(1);
//        }
//    });

    
});